// pages/add/add.js
const app = getApp();
const url = app.globalData.url;
//引入图片预加载组件
const ImgLoader = require('../../template/img-loader/img-loader.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user:'',
    flv:[0,0],
    mzsm:false,
    addData:{
      zdday:0,
      jb:0,
      ispl:1
    },
    fllist:[],
    imgList:[],
    fbs:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (o) {
    console.log(o);
    this.imgLoader = new ImgLoader(this, this.imageOnLoad.bind(this))
    // this.peizi();
  },
  //提示
  showtt(tt,msg,btn,fhm){
    let that=this;
    wx.showModal({
      title:tt,
      content:msg,
      showCancel: true,//是否显示取消按钮
      cancelText: btn[0],//默认是“确定”
      confirmText: btn[1],//默认是“确定”
      success: function (res) {
        if (res.cancel) {
          //点击取消,默认隐藏弹框
          // if (options.finish) {
            if(!fhm){
              wx.navigateBack({ delta: 1 })
            }
          // }
        } else {
          if(tt=='提示'){
            wx.redirectTo({
              url:"/pages/vip/vip"
            })
          }else{
            that.setData({mzsm:true});
          }
        }
      },
      fail: function (res) { },//接口调用失败的回调函数
      complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  tszlwtw(){
    wx.showModal({
      title: "提示",
      content: "资料未填完,请认真检查",
      showCancel: false,//是否显示取消按钮
      // cancelText: btn[0],//默认是“确定”
      confirmText:"确认",//默认是“确定”
      success: function (res) {
        
      },
      fail: function (res) { },//接口调用失败的回调函数
      complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
    })
  },
  // 跳转url
  tourl(e){
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url:url
    })
  },
  //放大图片
  previewImage: function (e) {
    var src = e.currentTarget.dataset.src ; //获取data-src
    var imgList = this.data.imgList; //获取data-list
    //要把对象中需要的键值对拿出来，放进一个数组，Object.keys是为了取到对象的长度进行遍历
    var imgArr = [];
    var objkeys = Object.keys(imgList);
    for (var i = 0; i < objkeys.length; i++) {
      imgArr.push(imgList[i].url );
    }
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgArr // 需要预览的图片http链接列表
    })
  },
  // 设置主图
  swzt(e){
    console.log(e)
    if(e.currentTarget.dataset.i!=0){
      this.setData({ztxs:e.currentTarget.dataset.i});
    }
  },
  quxzt(){
    this.setData({ztxs:null})
  },
  szzts(e){
    let data = this.data.imgList;
    let th = this.data.imgList[0];
    let src=e.currentTarget.dataset.src;
    let xb=0;
    for (var j = 0; j < data.length; j++) {
      const item = data [j];
      if(item.url==src){
        xb=j;
      }
    }
    if(xb!=0){
      data[0]=data[xb];
      data[xb]=th;
      this.setData({imgList:data});
      this.quxzt();
    }
  },
  pdt(){
    if(this.data.peizi.xcx.fhyaddsf.txt==1||this.data.user.vip==2){
    }else{
      this.govip();
    }
  },
  // 置顶设置
  zdsz(e){
    if(this.data.peizi.xcx.fhyaddsf.txt==1||this.data.user.vip==2){
      this.setData({ "addData.zdday": e.detail.value});
    }else{
      this.setData({ "addData.zdday": 0});
    }
  },
  // 金币设置
  jb(e){
    if(this.data.peizi.xcx.fhyaddsf.txt==1||this.data.user.vip==2){
      var vipsfb = e.detail.value - (e.detail.value * this.data.peizi.xcx.ptss.txt);
      vipsfb = vipsfb.toFixed(2);
      this.setData({ "addData.jb": e.detail.value, vipsfb: vipsfb});
    }else{
      this.setData({ "addData.jb": 0});
    }
  },
  // 评论设置
  ispl(e){
    this.setData({ "addData.ispl": e.detail.value?1:2});
  },
  // 免责设置
  mzsm(e){
    this.setData({ "mzsm": e.detail.value});
  },
   // 配置文件
   peizi: function () {
    let that = this;
    app.fetch('api/wx/getpeizi', { dlx: 'xcxadd' }, "GET", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        wx.setNavigationBarTitle({
          title: data.data.xcxadd.title.txt
        });
        var vipfbjb = data.data.xcxadd.addjb.txt * data.data.xcxadd.fbvipzk.txt;
        vipfbjb=vipfbjb.toFixed(2);
        that.setData({
          peizi:data.data,
          "addData.jb":0,
          "addData.ll":data.data.xcxadd.qsll.txt,
          vipfbjb: vipfbjb,
        });
        that.setData({loding:false})
        // that.hquser();
        that.getfl();
        that.hqbqfl();
        that.hquser();
      } else {
        wx.showModal({
          title: '接口数据错误',
          content: '接口:"' + url + 'api/wx/getpeizi.php' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {

          },
          fail: function (res) { },//接口调用失败的回调函数
          complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
        })
      }
    })
  },
  // 获取分类
  getfl() {
    let that = this;
    let sj = {
      fldj: 1,
      lx: 1,
      pgs:50,
    };
    app.fetch('api/wx/getfl', sj, "POST", (err, data) => {
      console.log(data)
      var list=[];
      for(var i=0;i<data.data.length;i++){
        list[i]=data.data[i];
      }
      that.setData({
        'fllist[0]':list,
        click:data.data[0].fid
      });
      that.hqxfl();
    })
  },
  hqxfl(){
    let that = this;
    let sj = {
      fldj: 2,
      lx:1,
      pgs: 50,
      flid:that.data.click
    };
    app.fetch('api/wx/getfl', sj, "POST", (err, data) => {
      console.log(data)
      var list=[];
      for(var i=0;i<data.data.length;i++){
        list[i]=data.data[i];
      }
      that.setData({
        'fllist[1]':list,
      });
    })
  },
  hqbqfl(){
    let that = this;
    let sj = {
      fldj: 3,
      lx:1,
      pgs: 50,
    };
    app.fetch('api/wx/getfl', sj, "POST", (err, data) => {
      console.log(data)
      var list=[];
      for(var i=0;i<data.data.length;i++){
        list[i]=data.data[i];
      }
      that.setData({
        'flbq':list,
      });
      this.setData({ loding: false });
    })
  },
  xzfl1(e){
    let fl=this.data.fllist[e.detail.column][e.detail.value];
    if(e.detail.column==0){
      this.setData({click:fl.fid,"addData.fl[0]":e.detail.value,"addData.fl[1]":0});
      this.hqxfl();
    }
    if(e.detail.column==1){
      this.setData({"addData.fl[1]":e.detail.value});
      if(!this.data.addData.fl[0]){
        this.setData({"addData.fl[0]":0});
      }
    }
  },
  xzfl11(e){
    console.log(e)
    this.setData({
      "addData.fl":e.detail.value
    })
  },
  bq1(e){
    console.log(e)
    this.setData({
      "addData.bq":e.detail.value
    })
  },
  // 获取user信息;
  hquser() {
    let that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        app.fetch('api/wx/user', { openid: res.data }, "POST", (err, data) => {
          if (data.code == 200) {
            that.setData({ user: data.data[0], "addData.uid": data.data[0].uid})
            // that.getcsData();
            if((data.data[0].vip==2||data.data[0].addcs>0)&&!that.data.mzsm){
              that.showtt("免责声明",that.data.peizi.xcxmzsm.xtc.txt,["不同意","我同意"]);
            }else if(data.data[0].addcs==0){
              that.showtt("提示", "非会员一天只能发表" + that.data.peizi.xcx.fvipaddcs.txt+"次,会员无限制",["等一会","开会员"]);
            }
          }
        })
      },
      fail(){
        wx.showModal({
          title: '提示',
          content: '请先登录',
          success(res){
            if (res.cancel) {
              //点击取消,默认隐藏弹框
              // if (options.finish) {
                wx.navigateBack({ delta: 1 })
              // }
            } else {
                wx.redirectTo({
                  url: "/pages/my/my"
                })
            }
          }
        })
      }
    })
  },
  govip(){
    this.showtt("提示","非会员无法设置,请开通会员后设置",["等一会","开会员"],'bfh');
  },
  // 标题输入
  titleinput(e){
    this.setData({
      "addData.title":e.detail.value
    })
  },
  // 平台输入
  ptnameinput(e){
    this.setData({
      "addData.ptname":e.detail.value
    })
  },
  // 内容输入
  datalrinput(e){
    this.setData({
      "addData.datalr":e.detail.value
    })
  },
  // 上传logo图片
  addimglogo(){
    let that=this;
    let num = that.data.peizi.xcxadd.logos.txt - that.data.imgList.length;
    if(num>0){
      wx.chooseImage({
        count:num,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function(res) {
          var img = res.tempFilePaths;
          for (let p of img) {
            that.upload(p,'logo');
            console.log(p)
          }
        },
        fail: function(res) {},
        complete: function(res) {},
      })
    }else{
      wx.showToast({
        title: '一次最多'+that.data.peizi.xcxadd.logos.txt+'张图片',//提示文字
        duration: 1000,//显示时长
        mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false  
        image: '../../img/ico/clear.png', //图标，支持"success"、"loading"  
      })
    }
  },
  // 上传二维码图片
  addimgewm(){
    let that=this;
      wx.chooseImage({
        count:1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function(res) {
          var img = res.tempFilePaths;
          for (let p of img) {
            that.upload(p,'ewm');
            console.log(p)
          }
        },
        fail: function(res) {},
        complete: function(res) {},
      })
  },
  // 上传图片
  upload:function (img,lx) {
    wx.showToast({
      icon: "loading",
      title: "上传图片中..."
    });
    let that=this;
    wx.uploadFile({
      url: url + 'img/sctp.php', //接口
      filePath: img,
      name: 'file',
      formData: {
        'user': that.data.user.uid,
        lx:lx
      },
      success: function (res) {
        var data = res.data;
        if(!data.code){
          data = JSON.parse(data);
        }
        console.log(res)
        if (data.code == 200) {
          if(lx=='ewm'){
            var ewm=that.data.addData.ewm;
            if(ewm){
              ewm=ewm.substring(ewm.indexOf('img') + 4);
              that.delsc(ewm);
            }
            that.setData({"addData.ewm":url+data.uptp})
          }
          if(lx=='logo'){
            let imgList = that.data.imgList;
            let img = url +  data.ystp;
            let img1 = url +  data.uptp;
            let imgList1 = { url: img1, ys: img, loaded: false};
            imgList.push(imgList1);
            that.setData({  imgList: imgList });
            that.loadImages();
          }
        }
        //do something
      },
      fail: function (error) {
        console.log(error);
      }
    })
  },
  //删除图片
  clearimg: function (e) {
    wx.showLoading({
      title: '删除中...',
    })
    let that = this;
    let i = e.currentTarget.dataset.index;
    let tpList = this.data.tpList;
    let imgList = this.data.imgList;
    let upList = this.data.upList;
    let tp = [];
    let delimg = imgList[i].ys.substring(imgList[i].ys.indexOf('img')+4);
    wx.request({
      url: url + 'img/deltp.php', //接口地址
      data: {
        img: delimg
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" // 默认值
      },
      success(res) {
        console.log(res)
        if (res.data.code == 200) {
          let del ='uptp/'+ delimg.substring(delimg.indexOf('ystp') + 5);
          wx.request({
            url: url + 'img/deltp.php', //接口地址
            data: {
              img: del
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded" // 默认值
            },
            success(res) {
              console.log(res)
              if (res.data.code == 200) {
                for (let p of imgList) {
                  console.log(p)
                  if (p.url != imgList[i].url) {
                    console.log(p)
                    tp.push(p);
                  }
                  that.setData({ imgList: tp })
                }
                
              } else {
                wx.showModal({
                  title: '失败',
                  content: res.data,
                  showCancel: false,//是否显示取消按钮
                  cancelText: "否",//默认是“取消”
                  cancelColor: 'skyblue',//取消文字的颜色
                  confirmText: "是",//默认是“确定”
                  confirmColor: 'skyblue',//确定文字的颜色
                  success: function (res) {
                  },
                  fail: function (res) { },//接口调用失败的回调函数
                  complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
                })
              }
              wx.hideLoading()
            }
          })
        } else {
          wx.showModal({
            title: '失败',
            content: res.data,
            showCancel: false,//是否显示取消按钮
            cancelText: "否",//默认是“取消”
            cancelColor: 'skyblue',//取消文字的颜色
            confirmText: "是",//默认是“确定”
            confirmColor: 'skyblue',//确定文字的颜色
            success: function (res) {
            },
            fail: function (res) { },//接口调用失败的回调函数
            complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
          })
        }
        wx.hideLoading()
      }
    })
  },
   // 执行删除
   delsc: function (img) {
    let that = this;
    wx.request({
      url: url + 'img/deltp.php', //接口地址
      data: {
        img: img
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" // 默认值
      },
      success(res) {
        console.log(res)
      }
    })
  },
  loadImages() {
    //同时发起全部图片的加载 
    console.log(1)
    this.data.imgList.forEach(item => {
      this.imgLoader.load(item.url)
    })
  },
  //加载完成后的回调
  imageOnLoad(err, data) {
    console.log('图片加载完成', err, data.src)

    const imgList = this.data.imgList.map(item => {
      if (item.url == data.src)
        item.loaded = true
      return item
    })
    this.setData({ imgList })
  },
  czjb(sz, jb, tt, xlx) {
    let that = this;
    let sj = {
      uid: that.data.user.uid,
      sz: sz,
      jb: jb,
      tt: tt,
      lx: 'xcx',
      xlx: xlx ? xlx : ''
    };
    app.fetch('api/wx/czjb', sj, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        // that.hquser();
      }
    })
  },
  fbbtn(){
    let that=this;
    let user=that.data.user;
    let pz=that.data.peizi;
    let ad = that.data.addData;
    var fbjb = pz.xcxadd.addjb.txt;
    let zdjb = (ad.zdday * pz.xcxadd.zdjb.txt);
    if(user.vip==2){
      fbjb=that.data.vipfbjb;
      zdjb = (ad.zdday * pz.xcxadd.zdjb.txt * pz.xcxadd.zdvipzk.txt);
    }
    if(((user.jb)-zdjb-fbjb)>=0){
      var tt = '发布内容消耗了' + fbjb + "个" + that.data.peizi.xcx.jb.txt;
      that.czjb(2, fbjb, tt,"发布内容消耗了");
      if(ad.zdday!=0){
        var tt = '置顶内容消耗了' + zdjb + "个" + that.data.peizi.xcx.jb.txt;
        that.czjb(2, zdjb, tt, "置顶内容消耗了");
      }
      that.addfb();
    }else{
      wx.showModal({
        title: '提示:当前 ' + that.data.peizi.xcx.jb.txt +' 不足',
        content: "当前 " + that.data.peizi.xcx.jb.txt + ' 有: '+ user.jb+";发布需要: "+fbjb +" 个,置顶需要: "+zdjb+" 个",
        success(res) {
        }
      })
    }

  },
  addfb(){
    let that=this;
    let adddata=that.data.addData;
    let fllsit=that.data.fllist;
    let bq=that.data.flbq;
    let img=that.data.imgList;
    adddata.fid=fllsit[0][adddata.fl[0]].fid;
    adddata.flid=fllsit[1][adddata.fl[1]].fid;
    adddata.bqid=bq[adddata.bq].fid;
    adddata.vip=that.data.user.vip;
    adddata.issh = that.data.peizi.xcxadd.issh.txt;
    adddata.addcs=that.data.user.addcs;
    adddata.uname = that.data.user.uname ? that.data.user.uname : that.data.user.nickName;
    var imgs='';
    var ysimgs='';
    for(var p of img){
      imgs+=p.url.substring(p.url.indexOf('img'))+',';
      ysimgs+=p.ys.substring(p.ys.indexOf('img'))+",";
    }
    adddata.logolist = imgs.substring(0,imgs.length-1);
    adddata.logoyslist = ysimgs.substring(0, ysimgs.length - 1);
    adddata.ewm = adddata.ewm.substring(adddata.ewm.indexOf('img'));
    console.log(adddata);
    app.fetch('api/wx/addxq', { data: JSON.stringify(adddata) }, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        that.setData({ fbs: true, addData: '', imgList:[]});
        var tt="发布成功";
        var  ck=1;
        if(that.data.peizi.xcxadd.issh.txt==2){
          ck=2;
          tt="已提交后台审核";
        }
        wx.showToast({
          title: tt,
          icon: 'success',
          duration: 1000
        });
        setTimeout(function () {
          if(ck==1){
            wx.navigateBack({
              data: 1
            })
          }else{
            wx.redirectTo({
              url:"/pages/addlist/addlist?ck=2"
            })
          }
        }, 1000)
      }else{
        that.setData({ addData: {}, imgList:[]});
        wx.showModal({
          title: '提示',
          content: data.code.msg ,
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.peizi();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    let tp = that.data.imgList,ewm=that.data.addData.ewm;
    if (!this.data.fbs) {
      console.log("执行删除");
      if (tp.length > 0) {
        for (let p of tp) {
          let img = p.url.substring(p.url.indexOf('img') + 4);
          let img1 = p.ys.substring(p.ys.indexOf('img') + 4);
          that.delsc(img);
          that.delsc(img1);
        }
      }
      if (ewm) {
          let img = ewm.substring(ewm.indexOf('img') + 4);
          that.delsc(img);
      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})